package com.app.yourradioapp593.fragments;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.app.yourradioapp593.Config;
import com.app.yourradioapp593.R;
import com.app.yourradioapp593.activities.MainActivity;
import com.app.yourradioapp593.adapters.AdapterHomeCategory;
import com.app.yourradioapp593.adapters.AdapterHomeFeatured;
import com.app.yourradioapp593.adapters.AdapterHomeRadio;
import com.app.yourradioapp593.callbacks.CallbackHome;
import com.app.yourradioapp593.database.prefs.AdsPref;
import com.app.yourradioapp593.database.prefs.SharedPref;
import com.app.yourradioapp593.models.Category;
import com.app.yourradioapp593.models.Radio;
import com.app.yourradioapp593.rests.ApiInterface;
import com.app.yourradioapp593.rests.RestAdapter;
import com.app.yourradioapp593.utils.AdsManager;
import com.app.yourradioapp593.utils.Constant;
import com.app.yourradioapp593.utils.ItemOffsetDecoration;
import com.app.yourradioapp593.utils.NavigationType;
import com.app.yourradioapp593.utils.Tools;
import com.facebook.shimmer.ShimmerFrameLayout;

import java.util.ArrayList;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class FragmentHome extends Fragment {

    RelativeLayout lytParent;
    private View rootView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private Call<CallbackHome> callbackCall = null;
    private ShimmerFrameLayout lytShimmer;
    RelativeLayout lytContent;
    LinearLayout lytFeatured, lytCategory, lytRecent, lytRandom;
    ImageView imgArrowCategory, imgArrowRecent;
    LinearLayout nativeAdView;
    SharedPref sharedPref;
    AdsPref adsPref;
    AdsManager adsManager;
    private MainActivity activity;

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        activity = (MainActivity) context;
    }

    @SuppressWarnings("ConstantValue")
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_home, container, false);

        sharedPref = new SharedPref(activity);
        adsPref = new AdsPref(activity);
        adsManager = new AdsManager(activity);

        lytParent = rootView.findViewById(R.id.lyt_parent);
        if (Config.NAVIGATION_TYPE == NavigationType.BOTTOM_NAVIGATION) {
            lytParent.setPadding(0, 0, 0, getResources().getDimensionPixelSize(R.dimen.lyt_margin_bottom_navigation));
        } else {
            lytParent.setPadding(0, 0, 0, getResources().getDimensionPixelSize(R.dimen.lyt_margin_bottom_tab_layout));
        }

        lytShimmer = rootView.findViewById(R.id.shimmer_view_container);
        lytContent = rootView.findViewById(R.id.lyt_content);
        lytFeatured = rootView.findViewById(R.id.lyt_featured);
        lytCategory = rootView.findViewById(R.id.lyt_category);
        lytRecent = rootView.findViewById(R.id.lyt_recent);
        lytRandom = rootView.findViewById(R.id.lyt_random);
        swipeRefreshLayout = rootView.findViewById(R.id.swipe_refresh_layout);
        swipeRefreshLayout.setColorSchemeResources(R.color.color_light_primary);
        nativeAdView = rootView.findViewById(R.id.native_ad_view);

        imgArrowCategory = rootView.findViewById(R.id.img_arrow_category);
        imgArrowRecent = rootView.findViewById(R.id.img_arrow_recent);

        if (sharedPref.getIsDarkTheme()) {
            imgArrowCategory.setColorFilter(ContextCompat.getColor(activity, R.color.color_dark_icon));
            imgArrowRecent.setColorFilter(ContextCompat.getColor(activity, R.color.color_dark_icon));
        } else {
            imgArrowCategory.setColorFilter(ContextCompat.getColor(activity, R.color.color_light_icon));
            imgArrowRecent.setColorFilter(ContextCompat.getColor(activity, R.color.color_light_icon));
        }

        // on swipe list
        swipeRefreshLayout.setOnRefreshListener(() -> {
            if (callbackCall != null && callbackCall.isExecuted()) callbackCall.cancel();
            requestAction();
        });

        requestAction();

        Tools.setNativeAdStyle(activity, nativeAdView, Config.NATIVE_AD_STYLE_HOME);
        adsManager.loadNativeAdView(rootView, Config.NATIVE_AD_STYLE_HOME, Config.NATIVE_AD_HOME);

        return rootView;
    }

    private void requestAction() {
        showFailedView(false, "");
        showNoItemView(false);
        swipeProgress(true);
        new Handler().postDelayed(this::requestListPostApi, Constant.DELAY_PROGRESS);
    }

    private void requestListPostApi() {
        ApiInterface apiInterface = RestAdapter.createAPI(sharedPref.getBaseUrl());
        callbackCall = apiInterface.getHome(Config.REST_API_KEY);
        callbackCall.enqueue(new Callback<CallbackHome>() {
            @Override
            public void onResponse(@NonNull Call<CallbackHome> call, @NonNull Response<CallbackHome> response) {
                CallbackHome resp = response.body();
                if (resp != null && resp.status.equals("ok")) {
                    displayFeatured(resp.featured);
                    displayCategories(resp.categories);
                    displayRecent(resp.recent);
                    displayMostViewed(resp.views);
                    displayRandom(resp.random);
                    viewAll();
                } else {
                    onFailRequest();
                }
            }

            @Override
            public void onFailure(@NonNull Call<CallbackHome> call, @NonNull Throwable t) {
                if (!call.isCanceled()) onFailRequest();
            }

        });
    }

    private void viewAll() {
        rootView.findViewById(R.id.view_all_categories).setOnClickListener(v -> new Handler().postDelayed(() -> ((MainActivity) activity).selectCategory(), 250));
        rootView.findViewById(R.id.view_all_radios).setOnClickListener(v -> new Handler().postDelayed(() -> ((MainActivity) activity).selectRadio(), 250));
    }

    private void displayFeatured(final ArrayList<Radio> radios) {
        AdapterHomeFeatured mAdapter = new AdapterHomeFeatured(getActivity(), radios);
        RecyclerView recyclerViewFeatured = rootView.findViewById(R.id.recyclerViewFeatured);
        recyclerViewFeatured.setNestedScrollingEnabled(false);
        ItemOffsetDecoration itemDecoration = new ItemOffsetDecoration(activity, R.dimen.item_no_space);
        if (0 == recyclerViewFeatured.getItemDecorationCount()) {
            recyclerViewFeatured.addItemDecoration(itemDecoration);
        }
        recyclerViewFeatured.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL));
        recyclerViewFeatured.setAdapter(mAdapter);
        mAdapter.setItems(radios);

        mAdapter.setOnItemClickListener((view, obj, position) -> ((MainActivity) activity).onItemRadioClick(radios, position));

        mAdapter.setOnItemOverflowClickListener((view, obj, position) -> ((MainActivity) activity).showBottomSheet(obj));

        if (radios.size() == 0) {
            lytFeatured.setVisibility(View.GONE);
        }
    }

    private void displayCategories(final ArrayList<Category> categories) {
        AdapterHomeCategory mAdapter = new AdapterHomeCategory(getActivity(), categories);
        RecyclerView recyclerViewCategory = rootView.findViewById(R.id.recyclerViewCategory);
        recyclerViewCategory.setNestedScrollingEnabled(false);
        ItemOffsetDecoration itemDecoration = new ItemOffsetDecoration(activity, R.dimen.item_no_space);
        if (0 == recyclerViewCategory.getItemDecorationCount()) {
            recyclerViewCategory.addItemDecoration(itemDecoration);
        }
        recyclerViewCategory.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL));
        recyclerViewCategory.setAdapter(mAdapter);
        mAdapter.setItems(categories);

        mAdapter.setOnItemClickListener((view, obj, position) ->
                new Handler().postDelayed(() -> ((MainActivity) activity)
                        .openCategoryDetail(obj.cid, obj.category_name, obj.category_image, obj.radio_count), 0));

        if (categories.size() == 0) {
            lytCategory.setVisibility(View.GONE);
        }

    }

    private void displayRecent(final ArrayList<Radio> radios) {
        AdapterHomeRadio mAdapter = new AdapterHomeRadio(activity, radios);
        RecyclerView recyclerViewRecent = rootView.findViewById(R.id.recyclerViewRecent);
        recyclerViewRecent.setNestedScrollingEnabled(false);
        ItemOffsetDecoration itemDecoration = new ItemOffsetDecoration(activity, R.dimen.item_no_space);
        if (0 == recyclerViewRecent.getItemDecorationCount()) {
            recyclerViewRecent.addItemDecoration(itemDecoration);
        }
        recyclerViewRecent.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL));
        recyclerViewRecent.setAdapter(mAdapter);
        mAdapter.setItems(radios);

        if (Constant.item_radio.size() == 0) {
            Constant.item_radio.addAll(radios);
            activity.changeText(Constant.item_radio.get(0));
        }
        swipeProgress(false);
        if (radios.size() == 0) {
            showNoItemView(true);
        }

        mAdapter.setOnItemClickListener((view, obj, position) -> ((MainActivity) activity).onItemRadioClick(radios, position));

        mAdapter.setOnItemOverflowClickListener((view, obj, position) -> ((MainActivity) activity).showBottomSheet(obj));
    }

    private void displayMostViewed(final ArrayList<Radio> radios) {
        AdapterHomeRadio mAdapter = new AdapterHomeRadio(activity, radios);
        RecyclerView recyclerViewMostViewed = rootView.findViewById(R.id.recyclerViewMostViewed);
        recyclerViewMostViewed.setNestedScrollingEnabled(false);
        ItemOffsetDecoration itemDecoration = new ItemOffsetDecoration(activity, R.dimen.item_no_space);
        if (0 == recyclerViewMostViewed.getItemDecorationCount()) {
            recyclerViewMostViewed.addItemDecoration(itemDecoration);
        }
        recyclerViewMostViewed.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL));
        recyclerViewMostViewed.setAdapter(mAdapter);
        mAdapter.setItems(radios);

        if (Constant.item_radio.size() == 0) {
            Constant.item_radio.addAll(radios);
            activity.changeText(Constant.item_radio.get(0));
        }
        swipeProgress(false);
        if (radios.size() == 0) {
            showNoItemView(true);
        }

        mAdapter.setOnItemClickListener((view, obj, position) -> ((MainActivity) activity).onItemRadioClick(radios, position));

        mAdapter.setOnItemOverflowClickListener((view, obj, position) -> ((MainActivity) activity).showBottomSheet(obj));
    }

    private void displayRandom(final ArrayList<Radio> radios) {
        AdapterHomeRadio mAdapter = new AdapterHomeRadio(getActivity(), radios);
        RecyclerView recyclerViewRecent = rootView.findViewById(R.id.recyclerViewRandom);
        recyclerViewRecent.setNestedScrollingEnabled(false);
        ItemOffsetDecoration itemDecoration = new ItemOffsetDecoration(activity, R.dimen.item_no_space);
        if (0 == recyclerViewRecent.getItemDecorationCount()) {
            recyclerViewRecent.addItemDecoration(itemDecoration);
        }
        recyclerViewRecent.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL));
        recyclerViewRecent.setAdapter(mAdapter);
        mAdapter.setItems(radios);

        if (Constant.item_radio.size() == 0) {
            Constant.item_radio.addAll(radios);
            ((MainActivity) activity).changeText(Constant.item_radio.get(0));
        }
        swipeProgress(false);
        if (radios.size() == 0) {
            showNoItemView(true);
        }

        mAdapter.setOnItemClickListener((view, obj, position) -> ((MainActivity) activity).onItemRadioClick(radios, position));

        mAdapter.setOnItemOverflowClickListener((view, obj, position) -> ((MainActivity) activity).showBottomSheet(obj));
    }

    private void onFailRequest() {
        swipeProgress(false);
        if (Tools.isConnect(activity)) {
            showFailedView(true, getString(R.string.failed_text));
        } else {
            showFailedView(true, getString(R.string.failed_text));
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        swipeProgress(false);
        if (callbackCall != null && callbackCall.isExecuted()) {
            callbackCall.cancel();
        }
        lytShimmer.stopShimmer();
    }

    private void showFailedView(boolean show, String message) {
        View lyt_failed = rootView.findViewById(R.id.lyt_failed);
        ((TextView) rootView.findViewById(R.id.failed_message)).setText(message);
        if (show) {
            lytContent.setVisibility(View.GONE);
            lyt_failed.setVisibility(View.VISIBLE);
        } else {
            lytContent.setVisibility(View.VISIBLE);
            lyt_failed.setVisibility(View.GONE);
        }
        rootView.findViewById(R.id.failed_retry).setOnClickListener(view -> requestAction());
    }

    private void showNoItemView(boolean show) {
        View lyt_no_item = rootView.findViewById(R.id.lyt_no_item);
        ((TextView) rootView.findViewById(R.id.no_item_message)).setText(R.string.no_data_found);
        if (show) {
            lytContent.setVisibility(View.GONE);
            lyt_no_item.setVisibility(View.VISIBLE);
        } else {
            lytContent.setVisibility(View.VISIBLE);
            lyt_no_item.setVisibility(View.GONE);
        }
    }

    private void swipeProgress(final boolean show) {
        if (!show) {
            swipeRefreshLayout.setRefreshing(show);
            lytContent.setVisibility(View.VISIBLE);
            lytShimmer.setVisibility(View.GONE);
            lytShimmer.stopShimmer();
            return;
        } else {
            swipeRefreshLayout.setRefreshing(show);
            lytContent.setVisibility(View.GONE);
            lytShimmer.setVisibility(View.VISIBLE);
            lytShimmer.startShimmer();
        }
        swipeRefreshLayout.post(() -> {
            swipeRefreshLayout.setRefreshing(show);
            lytContent.setVisibility(View.GONE);
            lytShimmer.setVisibility(View.VISIBLE);
            lytShimmer.startShimmer();
        });
    }

}